package com.self.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.self.oss.service.OssService;
import com.self.oss.utils.ConstantPropertyUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {


    //上传讲师头像
    @Override
    public String uploadAvatar(MultipartFile file) {

        String endPoint = ConstantPropertyUtils.END_POINT;
        String bucketName = ConstantPropertyUtils.BUCKET_NAME;
        String accessKeyID = ConstantPropertyUtils.KEY_ID;
        String accessKeySecret = ConstantPropertyUtils.KEY_SECRET;

        System.out.println("OSS实验");
        try {
            //创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyID, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();

            System.out.println(ossClient);
            System.out.println(originalFilename);

            String uuid = UUID.randomUUID().toString().replace("-", "");
            String filename = uuid + originalFilename;

            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = datePath + "/" + filename;

            System.out.println(filename);

            ossClient.putObject(bucketName, filename, inputStream);

            ossClient.shutdown();

            String uploadUrl = "https://" + bucketName + "." + endPoint + "/" + filename ;

            System.out.println(uploadUrl);
            return uploadUrl;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
